package com.hmall.item.job;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * TODO
 *
 * @Author wangxinyi
 * @Date 2024/11/15 15:49
 */

/**
 * 每天凌晨3点执行一次任务，统计表中销量Top20的商品列表，保存到redis缓存中
 */
@Component
public class UpDateSoldJob {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

     @Scheduled(cron = "0 0 3 * * ? ")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void updateSold() {

        //统计表中销量Top20的商品列表，保存到redis缓存中
        //redis的大Key
        String key = "HotSold::";
        //从数据库中查出前20位销量高的商品，从高到低
        LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Item::getSold).last("limit 20");
        List<Item> itemList = itemMapper.selectList(lqw);
        //采用String存储结构,value为itemList
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(itemList));
    }
}
